﻿

using System.ComponentModel;

namespace Acl.Messages.Impl;

/// <summary>
/// 拥有释放标价的释放基类
/// </summary>
class BooleanDisposable : IDisposable
{
    [NonSerialized]
    private int _isDisposed = 0;

    private const int DisposedFlag = 1;

    /// <summary>
    /// 析构函数
    /// </summary>
    ~BooleanDisposable()
    {
        Dispose(false);
    }

    /// <summary>
    /// 执行与释放或重置非托管资源相关的应用程序定义的任务。
    /// </summary>
    public void Dispose()
    {
        this.Dispose(true);

        var isDisposed = _isDisposed;
        Interlocked.CompareExchange(ref _isDisposed, DisposedFlag, isDisposed);

        // 防止多次调用Dispose。
        if (isDisposed != 0)
        {
            return;
        }

        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// 判断当前对象是否释放
    /// </summary>
    [Browsable(false)]
    public bool IsDisposed
    {
        get
        {
            Thread.MemoryBarrier();
            return _isDisposed == DisposedFlag;
        }
    }

    /// <summary>
    /// 执行与释放或重置非托管资源相关的应用程序定义的任务。
    /// </summary>
    /// <param name="disposing"></param>
    protected virtual void Dispose(bool disposing)
    {

    }

    /// <summary>
    /// 检查对象是否还没有被释放
    /// </summary>
    /// <exception cref="ObjectDisposedException">如果对象已经释放则触发该异常</exception>
    protected virtual void CheckNotDisposed()
    {
        if (IsDisposed)
        {
            throw new ObjectDisposedException(GetType().Name);
        }
    }
}
